package com.xfcy.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xfcy.ucenter.mapper.XcUserMapper;
import com.xfcy.ucenter.mapper.XcUserRoleMapper;
import com.xfcy.ucenter.model.dto.AuthParamsDto;
import com.xfcy.ucenter.model.dto.XcUserExt;
import com.xfcy.ucenter.model.po.XcUser;
import com.xfcy.ucenter.model.po.XcUserRole;
import com.xfcy.ucenter.service.AuthService;
import com.xfcy.ucenter.service.WxAuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

/**
 * @author 晓风残月Lx
 * @date 2023/7/4 15:12
 * 微信扫码方式
 */
@Service("wx_authservice")
public class WxAuthServiceImpl implements AuthService, WxAuthService {

    @Value("${weixin.appid}")
    String appid;

    @Value("${weixin.secret}")
    String secret;

    @Autowired
    XcUserMapper xcUserMapper;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    XcUserRoleMapper xcUserRoleMapper;

    @Autowired
    WxAuthServiceImpl currentProxy;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {

        String username = authParamsDto.getUsername();

        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));

        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser, xcUserExt);

        return xcUserExt;
    }

    /**
     * 微信扫码认证
     *
     * @param code 授权码
     * @return
     */
    @Override
    public XcUser mxAuth(String code) {

        // 申请令牌
        Map<String, String> access_token_obj = getAccess_token(code);
        String access_token = access_token_obj.get("access_token");
        String openid = access_token_obj.get("openid");
        // 携带令牌查询用户信息
        Map<String, String> userInfo = getUserInfo(access_token, openid);
        if(userInfo==null){
            return null;
        }

        // 保存用户信息到数据库
        XcUser xcUser = currentProxy.addWxUser(userInfo);
        return xcUser;
    }

    /**
     * 申请令牌
     *
     * @param code
     * @return
     */
    private Map<String, String> getAccess_token(String code) {

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        // 最终的路径  替换%s
        String.format(url, appid, secret, code);

        // 远程调用此url
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, null, String.class);
        // 获取响应的结果
        String result = exchange.getBody();
        // 将result转为map
        Map<String, String> map = JSON.parseObject(result, Map.class);

        return map;
    }

    /**
     * 携带令牌查询用户信息
     * @param access_token
     * @param openid
     * @return
     */
    private Map<String, String> getUserInfo(String access_token, String openid) {

        String wxUrl_template = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";
        String.format(wxUrl_template, access_token, openid);

        ResponseEntity<String> exchange = restTemplate.exchange(wxUrl_template, HttpMethod.GET, null, String.class);

        String result = new String(exchange.getBody().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

        Map<String, String> map = JSON.parseObject(result, Map.class);
        return map;
    }

    @Transactional
    public XcUser addWxUser(Map userInfo_map) {
        String unionid = userInfo_map.get("unionid").toString();

        //根据unionid查询数据库
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getWxUnionid, unionid));
        if(xcUser!=null){
            return xcUser;
        }

        String userId = UUID.randomUUID().toString();
        xcUser = new XcUser();
        xcUser.setId(userId);
        xcUser.setWxUnionid(unionid);
        //记录从微信得到的昵称
        xcUser.setNickname(userInfo_map.get("nickname").toString());
        xcUser.setUserpic(userInfo_map.get("headimgurl").toString());
        xcUser.setName(userInfo_map.get("nickname").toString());
        xcUser.setUsername(unionid);
        xcUser.setPassword(unionid);
        xcUser.setUtype("101001");//学生类型
        xcUser.setStatus("1");//用户状态
        xcUser.setCreateTime(LocalDateTime.now());
        xcUserMapper.insert(xcUser);
        XcUserRole xcUserRole = new XcUserRole();
        xcUserRole.setId(UUID.randomUUID().toString());
        xcUserRole.setUserId(userId);
        xcUserRole.setRoleId("17");//学生角色
        xcUserRoleMapper.insert(xcUserRole);
        return xcUser;

    }


}
